# Copyright (c) Guillaume Fraux 2014-2015
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ============================================================================ #
#           Implementation of the XYZ trajectories Writer
#
# XYZ format is a text-based format, with atomic informations arranged as:
#      <name> <x> <y> <z> [<vx> <vy> <vz>]
# The two first lines of each frame contains a comment header, and the number
# of atoms.
# ============================================================================ #

type XYZWriter <: FormatWriter
    file::IOStream
    header::String
end

register_writer(extension="xyz", filetype="XYZ", writer=XYZWriter)

function XYZWriter(filename::String; kwargs...)
    header = get_in_kwargs(kwargs, :header, "Generated by Jumos")
    file = open(filename, "w")
    return XYZWriter(file, header)
end


function Base.write(traj::Writer{XYZWriter}, universe::Universe)
    header = traj.writer.header * "\n"
    natoms = string(size(universe.frame.positions, 2)) * "\n"
    write(traj.writer.file, natoms)
    write(traj.writer.file, header)
    write_xyz_data(traj.writer.file, universe)
end

function write_xyz_data(file::IO, universe::Universe; velocities=false)
   for i=1:size(universe.topology)
      line = @sprintf("%s %f %f %f",
                        universe.topology[i].label,
                        universe.frame.positions[i][1],
                        universe.frame.positions[i][2],
                        universe.frame.positions[i][3])
      if velocities
          line *= @sprintf(" %f %f %f",
                        universe.frame.velocities[i][1],
                        universe.frame.velocities[i][2],
                        universe.frame.velocities[i][3])
      end
      line *= "\n"
      write(file, line)
   end
end
